package com.relax;

import com.alibaba.csp.sentinel.slots.block.Rule;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;


@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients()
public class ServiceApiApplication {
    public static void main(String[] args) {
        initFlowRules();
        SpringApplication.run(ServiceApiApplication.class, args);
    }

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    private static void initFlowRules() {
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule();
        rule.setResource("sentinelTest");
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // Set limit QPS to 20.
        rule.setCount(1);
        rules.add(rule);
        FlowRuleManager.loadRules(rules);


        // 添加熔断规则  todo 不起作用啊
        DegradeRule degradeRule = new DegradeRule();
        degradeRule.setResource("sentinelTest");
        degradeRule.setCount(1000);
        degradeRule.setMinRequestAmount(1);
//        degradeRule.setGrade() todo 默认就是慢调用 RT
        List<DegradeRule> degradeRuleList = new ArrayList<>();
        degradeRuleList.add(degradeRule);

        DegradeRuleManager.loadRules(degradeRuleList);

        System.out.println("sentinel 规则配置完成--彭青松");
    }
}
